package org.dromara.common.core.validate.enumd

import jakarta.validation.ConstraintValidator
import jakarta.validation.ConstraintValidatorContext
import org.dromara.common.core.utils.reflect.ReflectUtils.invokeGetter

/**
 * 自定义枚举校验注解实现
 *
 * @author LikeYouDo
 */
open class EnumPatternValidator : ConstraintValidator<EnumPattern, String> {
    private lateinit var annotation: EnumPattern

    override fun initialize(annotation: EnumPattern) {
        super.initialize(annotation)
        this.annotation = annotation
    }

    override fun isValid(value: String?, constraintValidatorContext: ConstraintValidatorContext?): Boolean {
        if (!value.isNullOrBlank()) {
            val fieldName: String = annotation.fieldName
            for (e in annotation.type.java.enumConstants) {
                if (value == invokeGetter(e, fieldName)) {
                    return true
                }
            }
        }
        return false
    }
}
